<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of formbuilder
 *
 * @author Information
 */
class formbuilder {
    //put your code here
    public  $formdata = false;
    public $defaultdata = array();
    public function __construct($formdata = false) {
        $this->setForm($formdata);
    }

    public function setForm($formdata){
        $this->formdata = json_decode($formdata);
        if($formdata) {
            foreach($this->formdata->element as $k => &$v) {
                $v->element_name = $this->getFormNameFromFieldObject($v, $k);
            }
        }
    }

    public function getFormFieldNames(){
        $data = array();
        foreach($this->formdata->element as $k => $v) {
            $data[$k] = $v->element_name;
        }
        return $data;
    }

    public function getFormFieldTitles()
    {
        $data = array();
        foreach($this->formdata->element as $k => $v) {
            $data[$k] = $v->element_title;
        }
        return $data;
    }

    public function getFormElements()
    {
        return $this->formdata->element;
    }

    public function getFormHTML()
    {
        $html = "";
        $elements = $this->getFormElements();
        foreach($elements as $k => $f) {
            $html .= $this->getFieldHTML($f, $k) . "\n\r";
        }
        return $html;
    }

    public function getFormHTMLFromData($data)
    {
        $html = "";
        foreach($data as $k => $f) {
            $html .= $this->getFieldHTMLFromData($k, $f);
        }
        return $html;
    }

    public function getFormHTMLLightboxFromData($data) {
        $html = "";
        foreach($data as $k => $f) {
            $html .= $this->getFieldHTMLLightboxFromData($k, $f);
        }
        return $html;
    }

    public function getFieldLabelHTML($f) {
        return "<p style='line-height: 21px;' class='formfieldlabel'>{$f->element_title}: </p>\n\r";
    }

    public function setFormDefaultData($data) {
        $this->defaultdata = $data;
    }

    public function getOutputText($text) {
        return str_replace("\\'", "'", nl2br($text));
    }

    public function getFieldHTMLLightboxFromData($key, $fieldData) {
        $titleData = $this->parseFormFieldName($key);
        // check and replace out put text
        if(is_string($fieldData)) {
            $fieldData = $this->getOutputText($fieldData);
        }

        $firstFieldClassString = "";
        $fieldCssString = "margin-top: -22px;";
        if($titleData['key'] == "1") {
            $firstFieldClassString = "float:left;margin-top: 7px;";
            $fieldCssString = "margin-top: -10px;";
        }
        $html = "<p align='left' class='lightbox-normal-text-size' style='{$firstFieldClassString}font-weight: bold;'>{$titleData['title']}:</p>
                <br style='clear: both;' />
                <div style='width:100%;{$fieldCssString}height: 83px; background-image: url(images/boxbg.png);'>
                    <div style='padding: 14px;'>
                        <div style='height: 55px; overflow: auto;width: 100%;'>
            ";

        $type = $titleData['type'];

        switch ($type) {
            case 'text':
                $html .= "{$fieldData}\r\n";
                break;
            case 'radio':
                $html .= "{$fieldData}\r\n";
                break;
            case 'select':
                $html .= "{$fieldData}\r\n";
                break;
            case 'break':
                $html .= "<hr class='formbreak' />\r\n";
                break;
            case 'textarea':
                $html .= "{$fieldData}\r\n";
                break;
            case 'checkbox':
                $checkStr = "";
                $html .= "\r\n";
                foreach($fieldData as $fk => $fv) {
                    $html .= $checkStr . " " . $fv;
                    $checkStr = ",";
                }
                $html .= "\r\n";
                break;
            case 'option':
                $checkStr = "";
                $html .= "\r\n";
                foreach($fieldData as $fk => $fv) {
                    $html .= $checkStr . " " . $fk . ": " . $fv;
                    $checkStr = "<br/>\r\n";
                }
                $html .= "\r\n";
                break;
            case 'friendselector':
                $html .= "\r\n";
                // update anwer text 3 to answer text 2
                $fieldData = (array)$fieldData;
                if($fieldData['name'] != "") {
                    $friendNames = explode(", ", $fieldData['name']);
                    $friendIds = explode(", ", $fieldData['ids']);
                    foreach($friendNames as $k => &$v) {
                        $v = "<a target='_blank' href='http://www.facebook.com/profile.php?id={$friendIds[$k]}'>$v</a>";
                    }
                    $html .=  implode(", ", $friendNames);
                }
                $html .= "\r\n";
                break;
            case 'image':
                $html = "<p align='left' class='lightbox-normal-text-size' style='{$firstFieldClassString}font-weight: bold;'>{$titleData['title']}:</p><br style='clear: both;' />";
                
                $html .= "<center><a href='{$fieldData}' target='_blank'><img class='answerimg' src='{$fieldData}' /></a></center><br style='clear: both;' />\r\n";
                return $html;
                break;
            default:
                break;
        }
        $html .= "</div>
            </div>
        </div>
        <!-- <br style='clear: both;' />-->\r\n";
        return $html;
    }

    public function getFieldHTMLFromData($key, $fieldData) {
        $titleData = $this->parseFormFieldName($key);

        $html = "<div class='formfieldcontainer'>";
        $html .= "<p style='line-height: 21px;' class='formfieldlabel'>{$titleData['title']}: </p>\n\r";

        $type = $titleData['type'];

        switch ($type) {
            case 'text':
                $html .= "<div class='answerfield'>{$fieldData}</div>\r\n";
                break;
            case 'radio':
                $html .= "<div class='answerfield'>{$fieldData}</div>\r\n";
                break;
            case 'select':
                $html .= "<div class='answerfield'>{$fieldData}</div>\r\n";
                break;
            case 'break':
                $html .= "<hr class='formbreak' />\r\n";
                break;
            case 'textarea':
                $html .= "<div class='answerfield'>{$fieldData}</div>\r\n";
                break;
            case 'checkbox':
                $checkStr = "";
                $html .= "<div class='answerfield'>\r\n";
                foreach($fieldData as $fk => $fv) {
                    $html .= $checkStr . " " . $fv;
                    $checkStr = ",";
                }
                $html .= "</div>\r\n";
                break;
            case 'option':
                $checkStr = "";
                $html .= "<div class='answerfield'>\r\n";
                foreach($fieldData as $fk => $fv) {
                    $html .= $checkStr . " " . $fk . ": " . $fv;
                    $checkStr = "<br/>\r\n";
                }
                $html .= "</div>\r\n";
                break;
            case 'friendselector':
                $html .= "<div class='answerfield'>\r\n";
                // update anwer text 3 to answer text 2
                $fieldData = (array)$fieldData;
                if($fieldData['name'] != "") {
                    $friendNames = explode(", ", $fieldData['name']);
                    $friendIds = explode(", ", $fieldData['ids']);
                    foreach($friendNames as $k => &$v) {
                        $v = "<a target='_blank' href='http://www.facebook.com/profile.php?id={$friendIds[$k]}'>$v</a>";
                    }
                    $html .=  implode(", ", $friendNames);
                }
                $html .= "</div>\r\n";
                break;
            case 'image':
                $html .= "<div class='answerfield'><a href='{$fieldData}' target='_blank'><img class='answerimg' src='{$fieldData}' /></a></div>\r\n";
                break;
            default:
                break;
        }
        $html .= "</div>\r\n";
        return $html;

    }

    public function getFieldHTML($f, $k = 0){
        $html = "<div class='formfieldcontainer'>";
        //        $readonlyString = "";

        $type = $f->element_type;
        if($type != 'break'){
            $html .= $this->getFieldLabelHTML($f);
        }

        // check and set default value
        if($f->element_default_value == "undefined") {
            $f->element_default_value = "";
        }

        if(isset($this->defaultdata[$f->element_name])) {
            $f->element_default_value = $this->defaultdata[$f->element_name];
        }

        if($f->element_is_required == "1") {
            $f->element_is_required = "required";
        } else {
            $f->element_is_required = "";
        }

        switch ($type) {
            case 'text':
                $html .= "<input type='text' name='form[{$f->element_name}]' value='{$f->element_default_value}' class='element_size_{$f->element_size} {$f->element_is_required}' />";
                break;
            case 'radio':
                $html .= "<div class='form-radio'>";
                foreach($f->option as $r) {
                    $checkStr = "";
                    if($r->option_is_default == "1") {
                        $checkStr = " checked='' ";
                    }
                    $html .= "<input type='radio' name='form[{$f->element_name}]' value='{$r->option}' {$checkStr} /> {$r->option} <br/>\n\r";
                }
                $html .= "</div>";
                break;
            case 'select':
                $html .= "<select name='form[{$f->element_name}]' class='element_size_{$f->element_size}'>";
                foreach($f->option as $r) {
                    $checkStr = "";
                    if($r->option_is_default == "1") {
                        $checkStr = " selected='selected' ";
                    }
                    $html .= "<option value='{$r->option}' {$checkStr}> {$r->option} </option>\n\r";
                }
                $html .= "</select>";
                break;
            case 'break':
                $html .= "<hr class='formbreak' />";
                break;
            case 'textarea':
                $html .= "<textarea name='form[{$f->element_name}]' class='element_size_{$f->element_size} {$f->element_is_required}'>{$f->element_default_value}</textarea>";
                break;
            case 'checkbox':
                $html .= "<div class='form-checkbox'>";
                foreach($f->option as $r) {
                    $checkStr = "";
                    if($r->option_is_default == "1") {
                        $checkStr = " checked='checked' ";
                    }
                    $html .= "<input type='checkbox' name='form[{$f->element_name}][]' value='{$r->option}' {$checkStr} /> {$r->option} <br/>\n\r";
                }
                $html .= "</div>";
                break;
            case 'option':
                $html .= "<div class='form-option'>";
                $html .= "<table class='element_size_{$f->element_size}'>\n\r";
                $i = 0;

                $opsfirst = clone $f->option;
                $opsfirst = (array)$opsfirst;
                array_unshift($opsfirst,"None");
                foreach($opsfirst as $r) {
                    $html .= "<tr>\n\r";
                    if($i == 0) {
                        $html .= "<th></th>\n\r";
                    } else {
                        $html .= "<td>{$r->option_row}</td>\n\r";
                    }
                    $ops = clone $f->option;

                    foreach($ops as $r2) {
                        if($i == 0) {
                            $html .= "<th>{$r2->option_column}</th>";
                        } else {
                            $html .= "<td class='tdhaveinput'><input type='radio' name='form[{$f->element_name}][{$r->option_row}]' value='{$r2->option_column}' /></td>\n\r";
                        }
                    }
                    $html .= "</tr>";
                    $i++;
                }
                $html .= "</table>";
                $html .= "</div>";
                break;
            case 'friendselector':

                $html .= "<div style='border:1px solid #D2D2D2;padding: 2px;width: 474px;' id='jfmfs-container_{$k}'>Loading facebook friend selector...</div>
                          <script type='text/javascript'>

                            function FBFriendSelectorInit_{$k}() {
                            FB.api('/me', function(response) {
                                jQuery('#jfmfs-container_{$k}').jfmfs({
                                                            max_selected: 1,
                                                            max_selected_message: 'valgt (in {0} of {1} selected)',
                                                            friend_fields: 'id,name,last_name',
                                                            pre_selected_friends: [],
                                                            exclude_friends: [],
                                                            sorter: function(a, b) {
                                                                var x = a.last_name.toLowerCase();
                                                                var y = b.last_name.toLowerCase();
                                                                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
                                                            }
                                                });
                                });

                                jQuery('#jfmfs-container_{$k}').bind('jfmfs.selection.changed', function(e, data) {
                                    window.console && console.log('changed', data);
                                    var str = '';
                                    var uids = '';
                                    var sign = '';
                                    var m = data.length;

                                    for(d=0; d<m; d++) {
                                        str += sign + data[d].name;
                                        uids += sign + data[d].id;
                                        sign = ', ';
                                    }

                                    var e1 = document.getElementById('{$f->element_name}-name');
                                    e1.value = str;

                                    var e2 = document.getElementById('{$f->element_name}-ids');
                                    e2.value = uids;
                                });
                            }
                            window.setTimeout('FBFriendSelectorInit_{$k}()', 2000);
                            </script>

                ";
                $html .= "<input type='hidden' id='{$f->element_name}-name' name='form[{$f->element_name}][name]' value='' />
                          <input type='hidden' id='{$f->element_name}-ids' name='form[{$f->element_name}][ids]' value='' />";
                break;
            case 'image':
                
                $html .= "<input type='file' name='{$f->element_name}' value='{$f->element_default_value}' class='element_size_{$f->element_size} {$f->element_is_required}' />";
                $html .= "<input type='hidden' name='form[{$f->element_name}]' value='{$f->element_default_value}' class='element_size_{$f->element_size} {$f->element_is_required}' />";
                break;
                /*
                $html .= "
                    <div id='{$f->element_name}'></div>
                    <div clas='form-image' id='{$f->element_name}-image'></div>
                    <input type='hidden' id='id-{$f->element_name}' name='form[{$f->element_name}]' value='' class='' />
                    <ul style='display:none;' id='{$f->element_name}-separate-list'></ul>
                    <script type='text/javascript'>
                        function createUploader_{$k}(){
                            var uploader = new qq.FileUploader({
                                element: document.getElementById('{$f->element_name}'),
                                listElement: document.getElementById('{$f->element_name}-separate-list'),
                                action: '?action=upload',
                                template: '<div class=\"qq-uploader\">' +
                                    '<div class=\"qq-upload-drop-area\"><span>Drop files here to upload</span></div>' +
                                    '<div class=\"qq-upload-button\"></div>' +
                                    '<ul class=\"qq-upload-list\"></ul>' +
                                '</div>',
                                onComplete: function(id, file, r) {
                                        jQuery('#{$f->element_name}-image').html('<img class=\"element_size_{$f->element_size}\" src=\"' + r.url + '\" />');
                                        jQuery('#id-{$f->element_name}').val(r.url);
                                        jQuery.unblockUI();
                                },
                                multiple: false,
                                onSubmit: function(id,file) {
                                    jQuery.blockUI();
                                }
                            });
                        }
                        createUploader_{$k}();
                    </script>
                    ";                 
                 */
            default:
                break;
        }
        $html .= "</div>";
        return $html;
    }

    public function getFormNameFromFieldObject($object, $key) {
        $name = str_replace(array("'","\"",",", "!", "_", " "), array("","","","","","+"), $object->element_title);
//        $name = strtolower($name);
        $name = $object->element_type . "__" . $name . "__" . $key;
        return $name;
    }

    public function parseFormFieldName($fieldName){
        $arr = explode("__", $fieldName);
        $data = array(
            'type' => $arr[0],
            'name' => $arr[1],
            'key' => $arr[2],
            'title' => str_replace(array("","","","","","+"), array("'","\"",",", "!", "_", " ") , $arr[1])
        );
        return $data;
    }

    public function pdebug($f = false) {
        echo "<pre>";
        if($f) {
            print_r($f);
        } else {
            print_r($this->formdata);
        }
        die("<br/>End of debug");
    }

}

?>
